package com.cgtong.android.fragment;


import android.app.Dialog;
import android.content.Intent;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.util.DiffUtil;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.View;
import android.view.inputmethod.EditorInfo;
import android.widget.EditText;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.TextView;

import com.blankj.utilcode.util.KeyboardUtils;
import com.blankj.utilcode.util.LogUtils;
import com.blankj.utilcode.util.ToastUtils;
import com.cgtong.android.App;
import com.cgtong.android.R;
import com.cgtong.android.activity.ProblemDetailActivity;
import com.cgtong.android.adapter.ProblemFollowedAdapter;
import com.cgtong.android.base.BaseLazyFragment;
import com.cgtong.android.bean.ProblemBean;
import com.cgtong.android.callback.DiffCallBack;
import com.cgtong.android.mvp.contract.ProblemFollowedContract;
import com.cgtong.android.mvp.presenter.ProblemFollowedPresenter;
import com.cgtong.android.util.PostUtil;
import com.cgtong.android.widget.BaseDialog;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.zhouyou.http.exception.ApiException;
import com.zhouyou.http.model.ApiResult;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;

import static android.app.Activity.RESULT_OK;
import static com.cgtong.android.activity.ProblemDetailActivity.KEY_LIST_ITEM_POSITION;

/**
 * 我关注的案卷
 * by zhuqingchun
 */
public class ProblemFollowedFragment extends BaseLazyFragment implements ProblemFollowedContract.View {

    public static final String TAG = ProblemFollowedFragment.class.getSimpleName();
    @BindView(R.id.recycler_view)
    RecyclerView mRecyclerView;
    @BindView(R.id.swipe_layout)
    SwipeRefreshLayout mSwipeLayout;
    @BindView(R.id.search_bar_fl)
    FrameLayout mSearchBarFl;
    @BindView(R.id.search_txt)
    TextView mSearchTxt;
    @BindView(R.id.search_edt)
    EditText mSearchEdt;
    @BindView(R.id.clear_img)
    ImageView mClearImg;
    @BindView(R.id.search_fl)
    FrameLayout mSearchFl;
    private List<ProblemBean> mList;
    private ArrayList<ProblemBean> mNewList;
    private ProblemFollowedAdapter mAdapter;

    private ProblemFollowedContract.Presenter mPresenter;
    private String mSearchKey = "";


    @Override
    public int getLayoutId() {
        return R.layout.fragment_file_followed;
    }

    @Override
    public void initData() {
        mPresenter = new ProblemFollowedPresenter(this);
        mList = new ArrayList<>();
        mNewList = new ArrayList<>();
        initRecyclerView();

        //回车键搜索监听
        mSearchEdt.setImeOptions(EditorInfo.IME_ACTION_SEARCH);
        mSearchEdt.setOnEditorActionListener(new TextView.OnEditorActionListener() {
            @Override
            public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
                if (actionId == EditorInfo.IME_ACTION_SEARCH) {
                    mSearchKey = mSearchEdt.getText().toString();
                    mPresenter.httpProblemFollowedData(0, mSearchKey, true);
                    KeyboardUtils.hideSoftInput(mSearchEdt);
//                    mSearchEdt.setText("");
                    return false;
                }
                return false;
            }
        });
        //显示或隐藏清空按钮
        mSearchEdt.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                if (s.toString().length() == 0) {
                    mClearImg.setVisibility(View.GONE);
                    mSearchKey = "";
//                    loadDataByNet();
                } else {
                    mClearImg.setVisibility(View.VISIBLE);
                }
            }
        });

    }

    /**
     * 初始化列表
     */
    private void initRecyclerView() {
        mSwipeLayout.setColorSchemeResources(R.color.color_scheme);
        mSwipeLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {
                mPresenter.httpProblemFollowedData(0, mSearchKey, true);
            }
        });
        mRecyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));
        mAdapter = new ProblemFollowedAdapter(mList);
        mRecyclerView.setAdapter(mAdapter);
        mAdapter.setShowFollowIcon(false);
//        mRecyclerView.addItemDecoration(new RecycleViewDivider(getActivity(), LinearLayoutManager.HORIZONTAL, R.drawable.shape_horizontal_divider));
        mAdapter.setOnLoadMoreListener(new BaseQuickAdapter.RequestLoadMoreListener() {
            @Override
            public void onLoadMoreRequested() {
                long maxId = mAdapter.getItem(mAdapter.getItemCount() - 2).getId();
                mPresenter.httpProblemFollowedData(maxId, mSearchKey, false);

            }
        }, mRecyclerView);
        mAdapter.openLoadAnimation(BaseQuickAdapter.SLIDEIN_BOTTOM);
//        mAdapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
//            @Override
//            public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
//                ProblemBean problemBean = mAdapter.getItem(position);
//                boolean canDelete = false;
//                boolean canEvaluate = false;
//                //4已结案，5已评价，7未上报---->可以删除
//                if ((problemBean.getStatus() == 4 || problemBean.getStatus() == 5 || problemBean.getStatus() == 7) && App.getInstance().isOwnself(problemBean.getCreateUserId())) {
//                    canDelete = true;
//                }
//                //4已结案，5已评价---->显示评价栏
//                if ((problemBean.getStatus() == 4 || problemBean.getStatus() == 5) && App.getInstance().isOwnself(problemBean.getCreateUserId())) {
//                    canEvaluate = true;
//                }
//                Log.d(TAG, "点击位置-----------" + position);
//                Log.d(TAG, "problemBean-----------" + problemBean.toString());
//                ProblemDetailActivity.startForResult(ProblemFollowedFragment.this, problemBean.getId(), canDelete, canEvaluate, position);
//            }
//        });
        //关注用户
        mAdapter.setOnItemChildClickListener(new BaseQuickAdapter.OnItemChildClickListener() {
            @Override
            public void onItemChildClick(BaseQuickAdapter adapter, View view, int position) {
                if (view.getId() == R.id.root_ll) {
                    ProblemBean problemBean = mAdapter.getItem(position);
                    boolean canDelete = false;
                    boolean canEvaluate = false;
                    //4已结案，5已评价，7未上报---->可以删除
                    if ((problemBean.getStatus() == 4 || problemBean.getStatus() == 5 || problemBean.getStatus() == 7) && App.getInstance().isOwnself(problemBean.getCreateUserId())) {
                        canDelete = true;
                    }
                    //4已结案，5已评价---->显示评价栏
                    if ((problemBean.getStatus() == 4 || problemBean.getStatus() == 5) && App.getInstance().isOwnself(problemBean.getCreateUserId())) {
                        canEvaluate = true;
                    }
                    Log.d(TAG, "点击位置-----------" + position);
                    Log.d(TAG, "problemBean-----------" + problemBean.toString());
                    ProblemDetailActivity.startForResult(ProblemFollowedFragment.this, problemBean.getId(), canDelete, canEvaluate, position);
                }
//                long userId = mAdapter.getItem(position).getCreateUserId();
//                if (App.getInstance().isOwnself(userId)) {
//                    ToastUtils.showShort(getString(R.string.txt_cannot_follow_youself));
//                    return;
//                }
//                mPresenter.follow(userId, position);
            }
        });
//        mAdapter.setOnItemLongClickListener(new BaseQuickAdapter.OnItemLongClickListener() {
//            @Override
//            public boolean onItemLongClick(BaseQuickAdapter adapter, View view, int position) {
//                showCancelFollowDialog((ProblemBean) adapter.getItem(position), position);
//                return false;
//            }
//        });
    }

    private void showCancelFollowDialog(final ProblemBean item, final int position) {
        BaseDialog.create(getChildFragmentManager())
                .setLayoutRes(R.layout.layout_cancel_follow_dialog)
                .setViewListener(new BaseDialog.ViewListener() {

                    @Override
                    public void bindView(View view, final Dialog dialog) {
                        view.findViewById(R.id.confirm_txt).setOnClickListener(new View.OnClickListener() {
                            @Override
                            public void onClick(View v) {
                                mPresenter.follow(item.getId(), position);
                                dialog.cancel();
                            }
                        });
                        view.findViewById(R.id.cancel_txt).setOnClickListener(new View.OnClickListener() {
                            @Override
                            public void onClick(View v) {
                                dialog.cancel();
                            }
                        });


                    }
                }).setDimAmount(0.3f)
                .setCanCancelable(false).
                setGravity(Gravity.CENTER)
                .setStyle(R.style.CenterDialogTheme)
                .show();

    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        Log.d(TAG, "onActivityResult-------------------------------requestCode:" + requestCode + " resultCode:" + resultCode + " data:" + (data != null ? data.toString() : "null"));

        if (resultCode == RESULT_OK) {
            if (requestCode == ProblemDetailActivity.KEY_CODE_FOLLOW_PROBLEM) {
                int position = data.getIntExtra(KEY_LIST_ITEM_POSITION, -1);
                Log.d(TAG, "onActivityResult = " + position);
                if (position != -1) {
                    mAdapter.remove(position);
                    if (mAdapter.getItemCount() == 0) {
                        mAdapter.setNewData(null);
                        mAdapter.setEmptyView(R.layout.layout_empty);
                    }
                }
            }
        }
    }

    @Override
    protected void loadDataByNet() {
        mPresenter.httpProblemFollowedData(0, mSearchKey, true);
    }

    @Override
    protected void onDataReloadByNet(View v) {
        mSearchKey = "";
        loadDataByNet();
    }


    @Override
    public void setRefreshing(boolean isRefresh) {
        if (mSwipeLayout != null) {
            mSwipeLayout.setRefreshing(isRefresh);
        }
    }

    @Override
    public void setEnableLoadMore(boolean enableLoadMore) {
        mAdapter.setEnableLoadMore(enableLoadMore);
    }

    @Override
    public void onLoadMoreEnd(boolean isLoadMoreEnd) {
        mAdapter.loadMoreEnd(isLoadMoreEnd);
    }


    @Override
    public void onError(ApiException e) {
        PostUtil.postSuccessDelayed(loadService);
        mAdapter.setNewData(null);
        mAdapter.setEmptyView(R.layout.layout_error);
    }


    @Override
    public void onNullData() {
        PostUtil.postSuccessDelayed(loadService);
        mAdapter.setNewData(null);
        mAdapter.setEmptyView(R.layout.layout_empty);
    }


    @Override
    public void onDestroy() {
        super.onDestroy();
//        mPresenter.onDestroy();
    }

    @Override
    public void onHttpProblemFollowedDataSuccess(List<ProblemBean> datas, boolean isRefresh) {
        PostUtil.postSuccessDelayed(loadService);
        if (isRefresh) {
            mNewList.clear();
            mAdapter.setNewData(datas);
        } else {
            mAdapter.addData(datas);
        }
        mNewList.addAll(datas);//比较集合不同的List
        mAdapter.loadMoreComplete();
    }

    @Override
    public void onFollowSuccess(long id, int position, ApiResult result) {
        LogUtils.d("onfollowsuccess position = " + position + " newlist = " + mNewList.size() + " list = " + mList.size() + " adapter = " + mAdapter.getData().size());
        if (result.getCode() == 0) {
            List<ProblemBean> beanList = mAdapter.getData();
            for (int i = 0; i < beanList.size(); i++) {
                ProblemBean bean = beanList.get(i);
                if (bean.createUserId == id) {
                    ProblemBean newProblemBean = bean.cloneAll(bean);
                    if (newProblemBean.isCreateUserAttention == 1) {
                        newProblemBean.isCreateUserAttention = 0;
                    } else {
                        newProblemBean.isCreateUserAttention = 1;
                    }
                    mNewList.set(i, newProblemBean);
                }
            }

//            ProblemBean problemBean = mAdapter.getItem(position);
//            ProblemBean newProblemBean = problemBean.cloneAll(problemBean);
            if ("1".equals(result.getMsg())) {
                //关注成功
                ToastUtils.showShort("关注成功！");
//                newProblemBean.setIsCreateUserAttention(1);
            } else {
                //取消关注成功
                ToastUtils.showShort("取消关注成功！");
//                newProblemBean.setIsCreateUserAttention(0);
            }
//            mNewList.set(position, newProblemBean);

            DiffUtil.DiffResult diffResult = DiffUtil
                    .calculateDiff(new DiffCallBack(mAdapter.getData(), mNewList),
                            false);
            diffResult.dispatchUpdatesTo(mAdapter);

            mAdapter.setAllNewData(mNewList);

            mNewList.clear();
            mNewList.addAll(mAdapter.getData());
        } else {
            ToastUtils.showShort(result.getMsg());
        }
    }

    @OnClick({R.id.clear_img, R.id.search_bar_fl})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.clear_img:
                mSearchKey = "";
                mSearchEdt.setText("");
                KeyboardUtils.hideSoftInput(mSearchEdt);
                loadDataByNet();
                break;
            case R.id.search_bar_fl:
                mSearchFl.setVisibility(View.VISIBLE);
                mSearchTxt.setVisibility(View.GONE);
                KeyboardUtils.showSoftInput(mSearchEdt);
                break;
        }
    }

}
